﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tactics
{
    using HighlightArea = Dictionary<int, int>;

    class UnitSelected : ISelectionMode
    {
        HighlightArea highlight;
        Unit unitSelected;
        Player unitOwner;

        Func<Unit, Dictionary<int, int>> highlightFunc;

        public Unit SelectedUnit
        {
            get { return unitSelected; }
        }

        public Player UnitOwner
        {
            get { return unitOwner; }
        }
       
        public UnitSelected(Unit unit, Player player, Func<Unit, Dictionary<int, int>> highlightFuncIn)
        {
            highlightFunc = highlightFuncIn;

            if (TacticsEngine.Instance.Game.TurnManager.UnitTurn == null ||
                TacticsEngine.Instance.Game.TurnManager.UnitTurn == unit)
                highlight = highlightFunc(unit);
            else
                highlight = null;

            unitSelected = unit;
            unitOwner = player;
        }

        public ISelectionMode ClickUnit(Unit unit, Player player)
        {
            if (TacticsEngine.Instance.Game.TurnManager.UnitTurn != null &&
                TacticsEngine.Instance.Game.TurnManager.UnitTurn != unit)
                return null;

            if (unit != unitSelected && player == unitOwner)
            {
                return new UnitSelected(unit, player, highlightFunc);
            }

            return null;            
        }

        // clicked to move IF in highlight area, else deselect
        public ISelectionMode ClickNothing(Utility.Pair<int, int> coord)
        {
            if (IsInHighlightArea(coord))
            {
                CommandQueue.Instance.AddCommand(new Commands.MoveUnitWithPromptCommand(unitSelected, coord));
            }

            // either way we're moving or deselecting
            return this;
        }

        public Dictionary<int, int> GetHighlightArea()
        {
            return highlight;
        }

        private bool IsInHighlightArea(Utility.Pair<int, int> coord)
        {
            return highlight.ContainsKey(TacticsEngine.Instance.Game.AtCoord(coord));
        }
    }
}
